
#include <windows.h>
#include <shlwapi.h>
#include <shellapi.h>
#pragma comment(lib,"shlwapi.lib")

int WINAPI WinMain( __in HINSTANCE /*hInstance*/, __in_opt HINSTANCE /*hPrevInstance*/, __in_opt LPSTR /*lpCmdLine*/, __in int /*nShowCmd*/ )
{
    
    PROCESS_INFORMATION g_pi = {0};
    STARTUPINFO si;
    SecureZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    TCHAR szPath[MAX_PATH];
    GetModuleFileName(NULL, szPath, MAX_PATH);
    TCHAR* p = StrRChr(szPath, NULL, TEXT('\\'));
    if (p)
    {
        ++p;
        *p = 0;
    }
    lstrcat(szPath, TEXT("TOTALCMD.EXE"));
    //ShellExecute(NULL, TEXT("open"), szPath, NULL, NULL, SW_NORMAL);
    //ExitProcess(0);
    if(CreateProcess(szPath, NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &g_pi ))
    {
        // for some reason, TC may take a wrong interface if we don't call below line
        //Sleep(300);

        LPVOID lpAlloc = VirtualAllocEx(g_pi.hProcess, NULL, MAX_PATH, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        if (lpAlloc)
        {
            CHAR szBuf[MAX_PATH];
            GetModuleFileNameA(NULL, szBuf, MAX_PATH);
            CHAR* p = StrRChrA(szBuf, NULL, '\\');
            if (p) {
                ++p;
                *p = 0;
            }
            lstrcatA(szBuf, "TC.dll");
            DWORD dwWrite;
            if (WriteProcessMemory(g_pi.hProcess, lpAlloc, szBuf, MAX_PATH, &dwWrite))
            {
                WaitForInputIdle(g_pi.hProcess, 3000); // strange ~~
                //Sleep(1000);
                HANDLE hThread = CreateRemoteThread(g_pi.hProcess, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, lpAlloc, 0, &dwWrite);
                WaitForSingleObject(hThread, INFINITE);
            }
            VirtualFreeEx(g_pi.hProcess, lpAlloc, 0, MEM_RELEASE);
        }
        CloseHandle(g_pi.hThread);
        CloseHandle(g_pi.hProcess);
    }
    ExitProcess(0);
}